package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityApplyBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.adapter.ApplyDetailsAdapter
import com.shipwe.loans.ui.adapter.ApplyDurationAdapter
import com.shipwe.loans.ui.presenter.ApplyPresenter
import com.shipwe.loans.ui.view.IApplyView
import com.shipwe.loans.utils.AppDensityUtil
import com.shipwe.loans.utils.decoration.GridSpacingItemDecoration
import com.shipwe.loans.utils.decoration.LinearSpacingItemDecoration
import com.shipwe.loans.utils.dialog.ApplyAmountGuideDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.CustomProcessHelper
import com.shipwe.loans.utils.helper.TestAnalysisAddEvent
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import com.shipwe.permission.Permission
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/25 19:21
 * @Annotation：申请贷款
 */
class ActivityApply: ShipweActivity(),IApplyView {
    lateinit var binding: ActivityApplyBinding
    private var presenter: ApplyPresenter? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    //选择时间
    private var durationAdapter: ApplyDurationAdapter? = null
    //贷款明细
    private var detailsAdapter: ApplyDetailsAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, ActivityApply::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getShipweRootView(): View {
        binding = ActivityApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnRes(R.drawable.back_black)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle(getString(R.string.apply_title))

        initApplyRefrashView()
        initApplyDurationGridView()
        initApplyDetailsListView()
        //提交申请获得积分数量
        binding.applyAddPoints.text = String.format(getString(R.string.points_add_count), CustomConfigsHelper.getShipweLoanApplyPoints())
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,getApplyProductName(),getApplyProductToken())
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,eventRemark)
        }
        binding.applyTotalSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                binding.applyTotal.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                presenter!!.loadApplyDetailsAction()
            }
        })
        //提交
        binding.applyConfirm.setOnClickListener {
            showShipweLoading(isTOuchOut = false, isCancel = true)
            presenter!!.submitApplyAction()
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOAN_APPLY_SUBMIT,eventRemark)
        }
    }

    override fun initShipweData() {
        showShipweLoading(isTOuchOut = false, isCancel = true)
        if (presenter == null){
            presenter = ApplyPresenter(this)
        }
        binding.applyContent.visibility = View.INVISIBLE
        presenter!!.loadApplyDetailsAction()
    }

    /* 初始化刷新 */
    private fun initApplyRefrashView() {
        //禁止加载
        binding.applyRefresh.setEnableLoadMore(false)
        binding.applyRefresh.setEnableAutoLoadMore(false)
        binding.applyRefresh.setOnRefreshListener {
            presenter!!.loadApplyDetailsAction()
        }
        binding.applyRefresh.setOnLoadMoreListener {
            binding.applyRefresh.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initApplyDurationGridView(){
        binding.applyDurationGridView.setHasFixedSize(true)
        binding.applyDurationGridView.isNestedScrollingEnabled = false
        binding.applyDurationGridView.isFocusableInTouchMode = false //不需要焦点
        val decoration = AppDensityUtil.dp2px(9f)
        binding.applyDurationGridView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.applyDurationGridView.layoutManager = layoutManager
        durationAdapter = ApplyDurationAdapter(binding.applyDurationGridView)
        durationAdapter!!.setOnItemChildClickListener { _, _, position ->
            val item = this.durationAdapter!!.getItem(position)
            if (!item.optBoolean("isEnabled",true) || item.optBoolean("isSelect",false)){
                return@setOnItemChildClickListener
            }
            for (i in 0..<durationAdapter!!.itemCount){
                val model = durationAdapter!!.getItem(i)
                model.put("isSelect",false)
                if (i == position){
                    model.put("isSelect",true)
                }
            }
            durationAdapter!!.notifyDataSetChanged()

            //刷新数据
            presenter!!.loadApplyDetailsAction()
        }
        binding.applyDurationGridView.adapter = durationAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initApplyDetailsListView() {
        binding.applyDetailsListView.setHasFixedSize(true)
        binding.applyDetailsListView.isNestedScrollingEnabled = false
        binding.applyDetailsListView.isFocusableInTouchMode = false //不需要焦点
        val decoration = AppDensityUtil.dp2px(14f)
        binding.applyDetailsListView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,decoration))
        binding.applyDetailsListView.layoutManager = LinearLayoutManager(this)
        detailsAdapter = ApplyDetailsAdapter(binding.applyDetailsListView)
        binding.applyDetailsListView.adapter = detailsAdapter!!
        binding.applyDetailsListView.itemAnimator = DefaultItemAnimator()
        detailsAdapter!!.setOnItemChildClickListener{ _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 获取查看的产品名称
     */
    override fun getApplyProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun getApplyProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取贷款金额
     */
    override fun getApplyAmount(): String {
        return binding.applyTotal.text.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getApplyDuration(): String {
        var days = ""
        if (durationAdapter!!.itemCount > 0){
            for (i in 0..<durationAdapter!!.itemCount){
                val item = durationAdapter!!.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    days = item.optString("day")
                    break
                }
            }
        }
        return days
    }

    /**
     * 不可选择贷款额度
     */
    override fun showApplyNotOptionalViews() {
        binding.applyTotalSeekBar.visibility = View.GONE
        binding.chooseTotalViewGroup.visibility = View.GONE
    }

    /**
     * 允许选择贷款额度
     */
    override fun showApplyOptionalViews(data: JSONObject) {
        binding.applyTotalSeekBar.visibility = View.VISIBLE
        binding.chooseTotalViewGroup.visibility = View.VISIBLE

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        mMinProcess = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //颗粒度
        mScale = data.optInt("granularity")

        //设置最大值
        val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
        binding.applyTotalSeekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.applyTotalSeekBar.progress = showAmount

        binding.applyMinPrice.text = "$mMinProcess"
        binding.applyMaxPrice.text = maxAmount

        //是否显示过引导指引
        val isShowGuide = ShipweSharedHelper.getShipweSharedBoolean(ShipweSharedKey.SHIPWE_DIALOG_GUIDE_SHOW)
        if (!isShowGuide){
            val guide = ApplyAmountGuideDialog(this,amount,object : ApplyAmountGuideDialog.IDialogCallback{
                override fun onGuideDismiss() {
                    ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_DIALOG_GUIDE_SHOW,true)
                    //设置当前值
                    binding.applyTotalSeekBar.progress = showAmount
                }
            })
            guide.setCancelable(false)
            guide.setCanceledOnTouchOutside(false)
            guide.show()
        }
    }

    /**
     * 设置贷款期限
     */
    override fun showApplyDurationList(data: JSONObject) {
        if (durationAdapter!!.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    obj.put("isEnabled",true)
                    dayList.add(obj)
                }
            } else {
                val obj = JSONObject()
                obj.put("day",defaultDays)
                obj.put("isSelect",true)
                obj.put("isEnabled",true)
                dayList.add(obj)
            }
            durationAdapter!!.data = dayList
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showApplyDetailsList(data: JSONObject) {
        binding.applyContent.visibility = View.VISIBLE
        binding.applyUnit.text = data.optString("currency")
        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.applyTotal.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    dataList.add(item)
                }
            }
            for (i in 0..<dataList.size){
                val obj = dataList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }
        detailsAdapter!!.data = dataList
    }

    /**
     * 贷款申请成功
     */
    override fun showApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //刷新产品列表
        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PRODUCT_REFRESH))

        dismissShipweLoading()
        //是否包含SMS权限
        val permissionList = CustomConfigsHelper.getShipwePermissionsList()
        if (permissionList.contains(Permission.READ_SMS)){
            //进入SMS权限使用说明页面
            ActivityApplySmsData.start(this,getApplyProductName(),getApplyProductToken())
            finish()
        } else {
            //刷新主流程
            publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PROCESS_REFRESH))
        }
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showApplyFailed() {
        dismissShipweLoading()
        finish()
    }

    override fun dismissShipweLoading() {
        super.dismissShipweLoading()
        binding.applyRefresh.finishRefresh()
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_PROCESS_REFRESHED -> {
                //需要校验 WhatsApp 或 SMS
                if (CustomProcessHelper.isCheckWhatsApp() || CustomProcessHelper.isCheckSMS()){
                    ActivityCheckNumber.start(this,getApplyProductName(),getApplyProductToken())
                }
                finish()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${getApplyProductName()} LoanApply Page"
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_APPLY_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_APPLY_END,eventRemark)
    }
}